package com.woniu.filter;

import org.springframework.stereotype.Component;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class CrossFilter
 * @author Gateway
 */
@WebFilter("/*")
@Component
public class CrossFilter implements Filter {

    /**
     * Default constructor. 
     */
    public CrossFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse resp=(HttpServletResponse) response;
		resp.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");//允许跨域的域,地址填写自己的当前页面的的网址
		resp.setHeader("Access-Control-Allow-Credentials", "true");//允许写cookie
		resp.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");//允许的请求方式
		resp.addHeader("Access-Control-Allow-Headers", "Orgin,Content-Type, x-requested-with, X-Custom-Header,Accept");//允许的类型
		resp.addHeader("Access-Control-Max-Age", "1800");// 30 min
		chain.doFilter(req, resp);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
